package com.longmao.oss.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.longmao.oss.service.UploadFileService;
import com.longmao.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author longmao
 * @date 2022/1/25 10:52
 * Content:
 */
@Service
public class UploadFileServiceImpl implements UploadFileService {
    /**
     * 上传文件流
     * @param file
     * @return
     */
    @Override
    public String UploadFileOss(MultipartFile file) {

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ConstantPropertiesUtil.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        String fileName = null;

        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            //获取上传文件流
            InputStream inputStream = file.getInputStream();
            fileName = file.getOriginalFilename();

            //1、给文件名称添加一个随机值，保证唯一
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //2、文件按照日期进行分类
            String datePath = new DateTime().toString("yyyy-MM-dd");

            fileName = datePath + "/" + uuid + fileName;

            //文件上传至阿里云 bucket名称、文件路径和文件名称、上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //获取url地址
            return "http://" + bucketName + "." + endpoint + "/" + fileName;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
